package com.backstage.productModule.controller;


import com.backstage.productModule.pojo.Commodity;
import com.backstage.productModule.pojo.Details;
import com.backstage.productModule.service.CommodityService;
import com.backstage.productModule.service.DetailsService;
import com.backstage.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 二级列表 前端控制器
 * </p>
 *
 * @author sakura
 * @since 2022-12-14
 */
@RestController
@RequestMapping("commodity")
@CrossOrigin
public class CommodityController {
    @Autowired
    private CommodityService commodityService;

    @Autowired
    private DetailsService detailsService;


    /**
     * 添加商品
     * @param commodity
     * @return
     */
    @PostMapping("save")
    public R save(@RequestBody Commodity commodity) {
        return commodityService.save(commodity) ? R.ok():R.error();
    }


    /**
     * 根据ID删除二级列表
     *
     * @param id
     * @return
     */
    @DeleteMapping("removeById/{id}")
    public R deleteById(@PathVariable Long id) {
        QueryWrapper<Details> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Mobile_end_CommodityId", id);
        List<Details> list = detailsService.list(queryWrapper);
        //判断下面是否还有商品  如果没有直接删除  如果有不能删除
        if (CollectionUtils.isEmpty(list))
            return commodityService.removeById(id) ? R.ok() : R.error();
        else
            return R.error("此目录下还有商品，无法删除!");
    }


    /**
     * 根据二级列表id修改信息
     *
     * @param commodity
     * @return
     */
    @PostMapping("updateById")
    public R update(@RequestBody Commodity commodity) {
        return commodityService.updateById(commodity) ? R.ok() : R.error();
    }

}

